package MainControl;

import Instrument.TestingMachine;
import Tool.GlobalVariable;
import Tool.XMLReader;

import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;

public class MainControl implements Runnable {

    private volatile static MainControl mainControl;

    static SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String remark = "";// 定义波轮还是滚筒，添加控制台信息使用

    // 设置重新初试话Socket,其中machineNo为configure中的TotalTestUnitID的value
    public synchronized static void reInit(Integer machineNo) {
        System.out.println("In reInit-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-");
        XMLReader configureReader = XMLReader.getInstance();
        //初始化保存台位网络信息的实体类
        TestingMachine tempMachine = new TestingMachine();
        tempMachine.setIP(configureReader.getIPbyID(String.valueOf(machineNo)));
        tempMachine.setPort(configureReader.getPortbyID(String.valueOf(machineNo)));
        tempMachine.setTotalTestUnitID(String.valueOf(machineNo));
        //將初始化好的對象存放到全局變量中
        GlobalVariable.machines.remove(tempMachine);
        GlobalVariable.machines.put(machineNo, tempMachine);
        Socket tempSocket=null;
        OutputStream tempWriter=null;
        InputStream tempReader=null;
        try {
            tempSocket = new Socket();
            tempSocket.connect(new InetSocketAddress(tempMachine.getIP(), Integer.parseInt(tempMachine.getPort())), 1000);
            tempSocket.setSoTimeout(1000);
            tempSocket.setKeepAlive(true);
            GlobalVariable.connections.remove(tempSocket);
            GlobalVariable.connections.put(machineNo, tempSocket);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (tempSocket != null) {
            try {
                tempWriter = tempSocket.getOutputStream();
                GlobalVariable.commandWriters.remove(machineNo);
                GlobalVariable.commandWriters.put(machineNo, tempWriter);
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                tempReader = tempSocket.getInputStream();
                GlobalVariable.dataReaders.remove(machineNo);
                GlobalVariable.dataReaders.put(machineNo, tempReader);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (GlobalVariable.collectionThreads.containsKey(machineNo)) {
                GlobalVariable.collectionThreads.get(machineNo).collectionSocket = tempSocket;
                GlobalVariable.collectionThreads.get(machineNo).collectionOutStream = tempWriter;
                GlobalVariable.collectionThreads.get(machineNo).collectionInStream = tempReader;
                GlobalVariable.collectionThreads.get(machineNo).RestartThread();
                if (!GlobalVariable.runningThread.containsKey(machineNo)) {
                    CollectionThread c=GlobalVariable.collectionThreads.get(machineNo);
                    Thread t = new Thread(c);
                    GlobalVariable.runningThread.put(machineNo, t);
                    t.start();
                    GlobalVariable.collectionThreads.get(machineNo).SendCollectionCommand();
                }
                return;
            }
        }
        String modelTypeandIDin = null;
        boolean ifHasWriter = true;
        try {
            modelTypeandIDin = GlobalVariable.testingUnitsID.get(machineNo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        CollectionThread c = new CollectionThread(machineNo, modelTypeandIDin,
                tempSocket, tempWriter, tempReader);
        GlobalVariable.collectionThreads.put(machineNo, c);
        if (ifHasWriter == true)
            c.SendCollectionCommand();
        if (GlobalVariable.runningThread.containsKey(machineNo))
            return;
        Thread t = new Thread(c);
        GlobalVariable.runningThread.put(machineNo, t);
        t.start();
        System.out.println(format.format(new Date()) + "--------------台位" + machineNo + "初始化完成---------------");
    }

    // 创建单例
    public static MainControl getMainControl() {
        if (mainControl == null) {
            synchronized (MainControl.class) {
                if (mainControl == null) {
                    mainControl = new MainControl();
                }
            }
        }
        return mainControl;
    }

    // 使用多线程进行接收数据
    public void run() {
        try {
            ServerSocket dataBackServer = new ServerSocket(7002);
            GlobalVariable.dataBackSocket = dataBackServer.accept();
            if (GlobalVariable.dataBackSocket != null) {
                System.out.println("端口7002初始化成功");
            }
            GlobalVariable.databackStream = GlobalVariable.dataBackSocket.getOutputStream();
            if (GlobalVariable.databackWriter == null)
                GlobalVariable.databackWriter = new PrintWriter(GlobalVariable.databackStream);
            // 打开7003端口用来返回原始数据
            GlobalVariable.serverSocketHex = new ServerSocket(7003);
            GlobalVariable.socketHex = GlobalVariable.serverSocketHex.accept();
            if (GlobalVariable.socketHex != null) {
                System.out.println("端口7003初始化成功");
            }
            GlobalVariable.databackStreamHex = GlobalVariable.socketHex.getOutputStream();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        MainControl m = MainControl.getMainControl();
        System.out.println("-----------准备就绪,请开启主控----------");
        Thread t = new Thread(m);
        CommandControl c = CommandControl.getInstance();
        Thread t1 = new Thread(c);
        t.start();
        t1.start();
    }
}
